package com.baijiayun.liveuibase.toolbox.answerer;

import android.content.Context;
import android.graphics.drawable.Drawable;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baijiayun.livecore.models.LPAnswerModel;
import com.baijiayun.livecore.models.LPAnswerSheetOptionModel;
import com.baijiayun.livecore.utils.LPLogger;
import com.baijiayun.liveuibase.R;
import com.baijiayun.liveuibase.base.BaseWindow;
import com.baijiayun.liveuibase.base.QueryPlus;
import com.baijiayun.liveuibase.utils.DisplayUtils;
import com.baijiayun.liveuibase.utils.ThemeDataUtil;
import com.baijiayun.liveuibase.utils.drawable.DrawableBuilder;
import com.baijiayun.liveuibase.utils.drawable.StateListDrawableBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class AnswererWindow extends BaseWindow implements AnswererContract.View {
    private AnswererContract.Presenter presenter;
    private boolean canSubmit = true;
    private QueryPlus c$, s$;
    private TextView tvSubmit, tvEndTimeTip, tvRemark;
    private ObservableEmitter<List<LPAnswerSheetOptionModel>> emitter;

    public AnswererWindow(Context context, LPAnswerModel lpAnswerModel) {
        super(context);
        presenter = new AnswererPresenter(this,routerListener);
        presenter.setAnswererDatas(lpAnswerModel);
    }


    private Drawable getSubmitDrawable(Context context) {
        final Drawable normalDrawable = new DrawableBuilder()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build();
        final Drawable disableDrawable = new DrawableBuilder()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context,R.attr.base_theme_dialog_negative_bg_color))
                .cornerRadius(context.getResources().getDimensionPixelSize(R.dimen.bjy_base_common_bg_radius))
                .build();
        return new StateListDrawableBuilder()
                .normal(normalDrawable)
                .disabled(disableDrawable)
                .build();
    }

    @Override
    public void initView(LPAnswerModel lpAnswerModel) {
        canSubmit = true;
        $.id(R.id.iv_close).invisible();
        TextView tvName = $.id(R.id.tv_name).view();
        tvName.setTextSize(12);
        LinearLayout llContainer = $.id(R.id.ll_container).view();
        llContainer.removeAllViews();
        View contentView = View.inflate(context, R.layout.uibase_answerer_window_student, null);
        c$ = QueryPlus.with(contentView);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        llContainer.addView(contentView, layoutParams);
        LinearLayout llOptionsContainer = c$.id(R.id.ll_options_container).view();
        tvSubmit = c$.id(R.id.tv_submit).view();
        tvSubmit.setBackground(getSubmitDrawable(context));
        compositeDisposable.add(c$.id(R.id.tv_submit).clicks().throttleFirst(500, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(o -> {
                    if (canSubmit) {
                        if (presenter.submitAnswers()) {
                            showToastMessage(getString(R.string.base_answerer_submit_success));
                            tvSubmit.setText(getString(R.string.base_answerer_modify));
                            canSubmit = false;
                            setClickable(llOptionsContainer, false);
                        } else {
                            showToastMessage(getString(R.string.base_answerer_submit_fail));
                            LPLogger.w("submit onError");
                        }
                    } else {
                        canSubmit = true;
                        presenter.reset();
                        setClickable(llOptionsContainer, true);
                        tvSubmit.setText(getString(R.string.base_answerer_submit));
                    }
                }));
        compositeDisposable.add(Observable.create((ObservableOnSubscribe<List<LPAnswerSheetOptionModel>>) emitter -> {
            this.emitter = emitter;
            emitter.onNext(lpAnswerModel.options);
        }).observeOn(AndroidSchedulers.mainThread())
                .filter(optionModelList -> {
                    for (LPAnswerSheetOptionModel lpAnswerSheetOptionModel : optionModelList) {
                        if (lpAnswerSheetOptionModel.isActive) {
                            return !tvSubmit.isEnabled();
                        }
                    }
                    tvSubmit.setEnabled(!canSubmit);
                    return false;
                })
                .subscribe(lpAnswerSheetOptionModel -> {
                    tvSubmit.setEnabled(true);
                }));
        tvEndTimeTip = contentView.findViewById(R.id.tv_endtime_tip);
        tvRemark = contentView.findViewById(R.id.tv_remark);
        tvRemark.setVisibility(TextUtils.isEmpty(lpAnswerModel.getDescription()) ? View.GONE : View.VISIBLE);
        tvRemark.setText(lpAnswerModel.getDescription());
        timeDown(lpAnswerModel.duration);
        List<LPAnswerSheetOptionModel> options = lpAnswerModel.options;
        if (lpAnswerModel.isJudgement()) {
            generateJudgementView(llOptionsContainer, options);
        } else {
            generateOptionsView(llOptionsContainer, options);
        }
    }

    /**
     * 提交成功，禁止点击
     */
    private void setClickable(View view, boolean isEnable) {
        view.setEnabled(isEnable);
        if (view instanceof ViewGroup) {
            ViewGroup parent = (ViewGroup) view;
            int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                View child = parent.getChildAt(i);
                setClickable(child, isEnable);
            }
        }
    }

    private void generateJudgementView(LinearLayout linearLayout, List<LPAnswerSheetOptionModel> options) {
        if (options.size() != 2) {
            LPLogger.w("judgement size more than 2 ,onError");
            showToastMessage(getString(R.string.base_answerer_judgement_error));
            return;
        }
        int size = options.size();
        for (int i = 0; i < size; i++) {
            LPAnswerSheetOptionModel lpAnswerSheetOptionModel = options.get(i);
            View itemView = View.inflate(context, R.layout.uibase_answerer_item_judgement, null);
            TextView tvOption = itemView.findViewById(R.id.tv_option);
            ImageView ivOption = itemView.findViewById(R.id.iv_option);
            ivOption.setBackground(new DrawableBuilder()
                    .oval()
                    .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                    .build());
            ImageView ivCheck = itemView.findViewById(R.id.iv_check);
            ivOption.setImageResource(i == 0 ? R.drawable.base_answer_judgement_right : R.drawable.base_answer_judgement_wrong);
            tvOption.setText(lpAnswerSheetOptionModel.text);
            ivCheck.setVisibility(lpAnswerSheetOptionModel.isActive ? View.VISIBLE : View.INVISIBLE);
            clickListener = new ClickListener(linearLayout, i);
            clickListener.options = options;
            ivOption.setOnClickListener(clickListener);
            ivCheck.setOnClickListener(clickListener);
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setGravity(Gravity.CENTER);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.leftMargin = DisplayUtils.dip2px(context, 12);
            layoutParams.rightMargin = DisplayUtils.dip2px(context, 12);
            layoutParams.topMargin = DisplayUtils.dip2px(context, 8);
            linearLayout.addView(itemView, layoutParams);
        }
    }

    /**
     * 是否是单选
     * @return
     */
    private boolean checkSingleOption(List<LPAnswerSheetOptionModel> options) {
        int rightCount = 0;
        for (LPAnswerSheetOptionModel optionModel : options) {
            if (optionModel.isCorrect || optionModel.isRight) {
                rightCount++;
            }
            if (rightCount >= 2) {
                return false;
            }
        }
        return true;
    }
    //单选题选中的iv
    private ImageView singleCheckedImageView;

    private Drawable getStateListDrawable(Context context) {
        final Drawable drawable = new DrawableBuilder().
                oval()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .build();
        final Drawable selectedDrawable = new DrawableBuilder().
                oval()
                .solidColor(ContextCompat.getColor(context,R.color.base_toolbar_red))
                .build();
        return new StateListDrawableBuilder()
                .normal(drawable)
                .selected(selectedDrawable)
                .build();
    }

    private void generateOptionsView(LinearLayout linearLayout, List<LPAnswerSheetOptionModel> options) {
        int size = options.size();
        LinearLayout newLayout = null;
        for (int i = 0; i < size; i++) {
            LPAnswerSheetOptionModel optionModel = options.get(i);
            View itemView = View.inflate(context, R.layout.uibase_answerer_item_check_option, null);
            TextView tvOption = itemView.findViewById(R.id.tv_option);
            tvOption.setBackground(getStateListDrawable(context));
            ImageView ivCheck = itemView.findViewById(R.id.iv_check);
            clickListener = new ClickListener(optionModel, ivCheck);
            clickListener.options = options;
            tvOption.setOnClickListener(clickListener);
            ivCheck.setOnClickListener(clickListener);
            ivCheck.setVisibility(optionModel.isActive ? View.VISIBLE : View.INVISIBLE);
            tvOption.setText(optionModel.text);
            if (i % 4 == 0) {
                newLayout = new LinearLayout(context);
                newLayout.setOrientation(LinearLayout.HORIZONTAL);
                newLayout.setGravity(Gravity.CENTER_HORIZONTAL);
                LinearLayout.LayoutParams newLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                newLayoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                linearLayout.setGravity(Gravity.CENTER);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.addView(newLayout, newLayoutParams);
            }
            LinearLayout.LayoutParams itemLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            itemLayoutParams.leftMargin = DisplayUtils.dip2px(context, 8);
            itemLayoutParams.rightMargin = DisplayUtils.dip2px(context, 8);
            itemLayoutParams.topMargin = DisplayUtils.dip2px(context, 8);
            newLayout.addView(itemView, itemLayoutParams);
        }
    }

    @Override
    protected View onCreateView(Context context) {
        setNeedShowShadow(true);
        final View view = View.inflate(context, R.layout.uibase_answerer_window, null);
        view.setBackground(ThemeDataUtil.getCommonWindowBg(context));
        allowTouch = false;
        return view;
    }

    @Override
    public void timeDown(long down) {
        if (tvEndTimeTip != null)
            tvEndTimeTip.setText(context.getString(R.string.base_answerer_endtime_countdown, getTimeString(down)));
    }

    @Override
    public void timeDownClose(long timeDown) {
        c$.id(R.id.tv_close_tip).text(context.getString(R.string.base_answerer_endtime_close, timeDown));
    }

    @Override
    public void doOnClose() {
        c$.id(R.id.tv_close_tip).visible();
        setClickable(c$.id(R.id.ll_options_container).view(), false);
        tvSubmit.setEnabled(false);
    }

    @Override
    public void endAnswer() {
        showToastMessage(getString(R.string.base_answerer_end));
        presenter.closeWindow();
    }

    private String getTimeString(long seconds) {
        long minute = seconds / 60;
        long second = seconds % 60;
        StringBuilder sb = new StringBuilder();
        if (minute < 10) {
            sb.append("0");
        }
        sb.append(minute);
        sb.append(":");
        if (second < 10) {
            sb.append("0");
        }
        sb.append(second);
        return sb.toString();
    }

    @Override
    public void onDestroy() {
        presenter.destroy();
        super.onDestroy();
    }

    @Override
    public void onReset(LPAnswerModel lpAnswerModel) {
        LinearLayout llOptionsContainer = c$.id(R.id.ll_options_container).view();
        tvSubmit.setEnabled(false);
        setClickable(llOptionsContainer, true);
        tvRemark.setVisibility(TextUtils.isEmpty(lpAnswerModel.getDescription()) ? View.GONE : View.VISIBLE);
        tvRemark.setText(lpAnswerModel.getDescription());
        c$.id(R.id.tv_close_tip).gone();
        llOptionsContainer.removeAllViews();
        if (lpAnswerModel.isJudgement()) {
            generateJudgementView(llOptionsContainer, lpAnswerModel.options);
        } else {
            generateOptionsView(llOptionsContainer, lpAnswerModel.options);
        }
        llOptionsContainer.requestLayout();
    }

    @Override
    public void onShowAnswer(LPAnswerModel lpAnswerModel) {
        showToastMessage(getString(R.string.base_answerer_end));
        $.id(R.id.iv_close).visible();
        $.id(R.id.iv_close).clicked(v -> presenter.closeWindow());
        TextView tvName = $.id(R.id.tv_name).view();
        tvName.setTextSize(12);
        tvName.setText(context.getString(R.string.base_tool_box_answerer));
        LinearLayout llContainer = $.id(R.id.ll_container).view();
        llContainer.removeAllViews();
        View answerView = View.inflate(context, R.layout.uibase_answer_show, null);
        s$ = QueryPlus.with(answerView);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        llContainer.addView(answerView, layoutParams);
        LinearLayout answerContainer = s$.id(R.id.ll_answer_container).view();
        List<LPAnswerSheetOptionModel> options = lpAnswerModel.options;
        List<String> myAnswers = new ArrayList<>();
        List<String> standardAnswers = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        int size = options.size();
        int rightIndex = -1;//判断题 index 0是✔ 1是x
        int myIndex = -1;//判断题 index 0是✔ 1是x
        for (int i = 0; i < size; i++) {
            LPAnswerSheetOptionModel optionModel = options.get(i);
            if (optionModel.isRight) {
                standardAnswers.add(optionModel.text);
                sb.append(optionModel.text);
                if (!lpAnswerModel.isJudgement()) {
                    sb.append(" ");
                } else {
                    rightIndex = i;
                }
            }
            if (optionModel.isActive) {
                myAnswers.add(optionModel.text);
                if (lpAnswerModel.isJudgement()) {
                    myIndex = i;
                }
            }
        }

        if (lpAnswerModel.isJudgement()) {
            showAnswerJudgement(answerContainer,myAnswers,myIndex,rightIndex);
        } else {
            showAnswerOption(answerContainer, myAnswers, standardAnswers);
        }
        String text = context.getString(R.string.base_answerer_right, sb.toString());
        s$.id(R.id.tv_standard_answer).text(text);
    }

    private void showAnswerJudgement(LinearLayout linearLayout,  List<String> myAnswers,int myIndex, int rightIndex) {
        int size = myAnswers.size();
        s$.id(R.id.tv_no_answer).visibility(size == 0 ? View.VISIBLE : View.GONE);
        linearLayout.setVisibility(size == 0 ? View.GONE : View.VISIBLE);
        if (size != 1) {
            return;
        }
        String text = myAnswers.get(0);
        boolean checked = myIndex != rightIndex;
        View itemView = View.inflate(context, R.layout.uibase_answerer_item_judgement, null);
        TextView tvOption = itemView.findViewById(R.id.tv_option);
        ImageView ivOption = itemView.findViewById(R.id.iv_option);
        ImageView ivCheck = itemView.findViewById(R.id.iv_check);
        tvOption.setText(text);
        ivCheck.setVisibility(View.GONE);
        int padding = DisplayUtils.dip2px(context, 4);
        ivOption.setPadding(padding,padding,padding,padding);
        ivOption.setImageResource(checked ? (myIndex == 0 ? R.drawable.base_show_answer_right_checked : R.drawable.base_show_answer_wrong_checked) :
                (myIndex == 0 ? R.drawable.base_answer_judgement_right : R.drawable.base_answer_judgement_wrong));
        Drawable checkDrawable = ContextCompat.getDrawable(context, R.drawable.base_bg_check_answerer_option_checked);
        final Drawable drawable = new DrawableBuilder().
                oval()
                .solidColor(ThemeDataUtil.getColorFromThemeConfigByAttrId(context, R.attr.base_theme_live_product_color))
                .build();

        ivOption.setBackground(checked ? checkDrawable : drawable);

        linearLayout.setOrientation(LinearLayout.HORIZONTAL);
        linearLayout.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.leftMargin = DisplayUtils.dip2px(context, 12);
        layoutParams.rightMargin = DisplayUtils.dip2px(context, 12);
        layoutParams.topMargin = DisplayUtils.dip2px(context, 12);
        layoutParams.bottomMargin = DisplayUtils.dip2px(context, 12);
        linearLayout.addView(itemView, layoutParams);
    }

    private void showAnswerOption(LinearLayout linearLayout, List<String> myAnswers, List<String> standardAnswers) {
        int size = myAnswers.size();
        s$.id(R.id.tv_no_answer).visibility(size == 0 ? View.VISIBLE : View.GONE);
        linearLayout.setVisibility(size == 0 ? View.GONE : View.VISIBLE);
        LinearLayout newLayout = null;
        for (int i = 0; i < size; i++) {
            String text = myAnswers.get(i);
            View itemView = View.inflate(context, R.layout.uibase_answerer_item_check_option, null);
            TextView tvOption = itemView.findViewById(R.id.tv_option);
            tvOption.setBackground(getStateListDrawable(context));
            itemView.findViewById(R.id.iv_check).setVisibility(View.GONE);
            tvOption.setText(text);
            tvOption.setSelected(!standardAnswers.contains(text));
            if (i % 4 == 0) {
                newLayout = new LinearLayout(context);
                newLayout.setOrientation(LinearLayout.HORIZONTAL);
                newLayout.setGravity(Gravity.CENTER_HORIZONTAL);
                LinearLayout.LayoutParams newLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                newLayoutParams.gravity = Gravity.CENTER_HORIZONTAL;
                linearLayout.setGravity(Gravity.CENTER);
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                linearLayout.addView(newLayout, newLayoutParams);
            }
            LinearLayout.LayoutParams itemLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            itemLayoutParams.leftMargin = DisplayUtils.dip2px(context, 8);
            itemLayoutParams.rightMargin = DisplayUtils.dip2px(context, 8);
            itemLayoutParams.topMargin = DisplayUtils.dip2px(context, 8);
            itemLayoutParams.bottomMargin = DisplayUtils.dip2px(context, 8);
            newLayout.addView(itemView, itemLayoutParams);
        }
    }

    private ClickListener clickListener;

    class ClickListener implements View.OnClickListener {
        private List<LPAnswerSheetOptionModel> options;
        private LPAnswerSheetOptionModel optionModel;
        private ImageView imageView;
        private LinearLayout linearLayout;
        private int index;

        public ClickListener(LPAnswerSheetOptionModel optionModel, ImageView imageView) {
            this.optionModel = optionModel;
            this.imageView = imageView;
        }

        public ClickListener(LinearLayout linearLayout, int index) {
            this.linearLayout = linearLayout;
            this.index = index;
        }

        @Override
        public void onClick(View v) {
            //选择题
            if (imageView != null) {
                final boolean singleOption = checkSingleOption(options);
                //单选题只允许选择一个选项
                if (singleOption) {
                    if (singleCheckedImageView != null) {
                        singleCheckedImageView.setVisibility(View.INVISIBLE);
                        final Object tag = singleCheckedImageView.getTag();
                        if (tag instanceof LPAnswerSheetOptionModel) {
                            LPAnswerSheetOptionModel optionModel = (LPAnswerSheetOptionModel) tag;
                            optionModel.isActive = false;
                        }
                    }
                    singleCheckedImageView = imageView;
                    singleCheckedImageView.setTag(optionModel);
                    optionModel.isActive = true;
                } else {
                    optionModel.isActive = !optionModel.isActive;
                }
                imageView.setVisibility(optionModel.isActive ? View.VISIBLE : View.INVISIBLE);
            }
            //判断题
            if (linearLayout != null) {
                int otherIndex = 1 - index;
                if (!options.get(index).isActive) {
                    options.get(index).isActive = true;
                    options.get(otherIndex).isActive = false;
                    linearLayout.getChildAt(index).findViewById(R.id.iv_check).setVisibility(View.VISIBLE);
                    linearLayout.getChildAt(otherIndex).findViewById(R.id.iv_check).setVisibility(View.INVISIBLE);
                }
            }
            if (emitter != null) {
                emitter.onNext(options);
            }
        }
    }
}
